﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace backend.Utils
{
    public class TokenHelper
    {
		#region 单例构造
		private static TokenHelper _instance;
		private TokenHelper() { }
		public static TokenHelper Instance()
		{
			if (_instance == null)
			{
				_instance = new TokenHelper();
			}
			return _instance;
		}
		#endregion

		public string GenerateToken(string userName,string roleName)
		{
			var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtParam.SecurityKey));
			var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
			var token = new JwtSecurityToken(
				JwtParam.Issure,
				JwtParam.Audience,
				new List<Claim>
				{
					new Claim(ClaimTypes.Name,userName),
					new Claim(ClaimTypes.Role, roleName),
				},
				notBefore: DateTime.UtcNow,
				expires: DateTime.UtcNow.AddDays(1),
				signingCredentials: credentials
			);
			return new JwtSecurityTokenHandler().WriteToken(token);
		}
	}
}
